package com.yanqingshan.platform.common.core.domain;

import com.yanqingshan.platform.common.constant.CommonConstant;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;

import java.io.Serializable;


/**
 * 功能描述: 自定义的统一返回对象
 * 响应信息主体
 *
 * @author yanqs
 * @since 2023-05-11
 */
@Data
public class R<T> implements Serializable {

    @ApiModelProperty(value = "返回码")
    private int code;


    @ApiModelProperty(value = "返回消息")
    private String msg;

    @ApiModelProperty(value = "返回数据")
    private T data;

    public static <T> R<T> ok() {
        return restResult(null, CommonConstant.SUCCESS, "请求成功");
    }

    public static <T> R<T> ok(T data) {
        return restResult(data, CommonConstant.SUCCESS, "请求成功");
    }

    public static <T> R<T> ok(T data, String msg) {
        return restResult(data, CommonConstant.SUCCESS, msg);
    }

    public static <T> R<T> failed() {
        return restResult(null, CommonConstant.FAIL, "系统异常");
    }

    public static <T> R<T> failed(String msg) {
        return restResult(null, CommonConstant.FAIL, msg);
    }

    public static <T> R<T> failed(T data) {
        return restResult(data, CommonConstant.FAIL, "系统异常");
    }

    public static <T> R<T> failed(T data, String msg) {
        return restResult(data, CommonConstant.FAIL, msg);
    }

    public static <T> R<T> failed(int code, T data, String msg) {
        return restResult(data, code, msg);
    }

    private static <T> R<T> restResult(T data, int code, String msg) {
        R<T> apiResult = new R<>();
        apiResult.setCode(code);
        apiResult.setData(data);
        apiResult.setMsg(msg);
        return apiResult;
    }

    /**
     * 返回R
     *
     * @param flag 成功状态
     * @return R
     */
    public static <T> R<T> status(boolean flag) {
        return flag ? ok() : failed();
    }

    public boolean ifOk() {
        return this.code == CommonConstant.SUCCESS;
    }
}
